var express = require("express");
var app = express();
const video = "./movie.mp4";
const fs = require("fs");
const { stat } = require("fs").promises;
var multiparty = require("multiparty");
app.use("/css", express.static("./public/css"));
app.use("/js", express.static("./public/js"));
app.use("/img", express.static("./public/img"));
app.use("/fonts", express.static("./public/fonts"));
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header(
    "Access-Control-Allow-Headers",
    "token,name,age,Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.header("X-Powered-By", "123");
  res.header("Access-Control-Expose-Headers", "setcookie,X-Powered-By");
  next();
});
app.post("/upla", (req, res) => {
  // 接收文件上传
  let form = new multiparty.Form({
    uploadDir: "./public/merge", //指定上传的文件路径
  });
  let imgName = req.query.name;
  let size = req.query.size;
  form.parse(req, (err, field, files) => {
    files &&
      files.file.map((x) => {
        // 必须这样写
        let img = imgName || x.originalFilename;
        fs.rename(x.path, "./public/merge/" + img, () => {
          if (size === imgName) {
            res.json({ ok: 200 }); // 判断分片全部完成
          } else {
            res.end(
              JSON.stringify({
                ok: 304,
              })
            );
          }
        });
      });
  });
  form.on("field", (name, value) => {
    // name:字段名
    // value:值
    console.log("数据:", name, value);
  });
  //接收文件数据
  form.on("file", (name, file) => {
    console.log("文件:", name, file);
  });
  //表单解析完成
  form.on("close", () => {
    console.log("完成");
  });
});
app.get("/merge", (req, res) => {
  // 触发上个分片接口成功回调发送请求
  let filePath = "./public/img/" + req.query.name;
  fs.readdir("./public/merge", (err, list) => {
    console.log(list);
    list.map((res) => {
      fs.appendFileSync(filePath, fs.readFileSync("./public/merge/" + res)); // 读取返回结果 然后追加路径
      fs.unlinkSync("./public/merge/" + res); // 删除分片
    });
    res.json({
      url: `http://localhost:4000/img/${req.query.name}`,
    });
  });
});

app.use("/demo", (req, res) => {
  res.json({
    ok: 200,
  });
});
app.get("/video", async (req, res) => {
  let range = req.headers["range"];
  if (range) {
    let stats = await stat(video);
    let r = range.match(/=(\d+)-(\d+)?/);
    console.log(range);
    let start = parseInt(r[1], 10);
    let end = r[2] ? parseInt(r[2], 10) : start + 1024 * 1024;
    if (end > stats.size - 1) end = stats.size - 1;
    let header = {
      "Content-Type": "video/mp4",
      "Content-Range": `bytes ${start} - ${end} / ${stats.size}`,
      "Content-Length": end - start + 1,
      "Accept-Ranges": "bytes",
    };
    res.writeHead(206, header);
    fs.createReadStream(video, { start: start, end: end }).pipe(res);
  } else {
    fs.createReadStream(video).pipe(res);
  }
});
app.listen(4000, () => {
  console.log("服务开启");
});
